
function myVue(options){
    this._init(options)
}
// 这里不能用箭头函数

myVue.prototype._init = function(options){
    this.$options = options 
    this.$data = options.data
    this.$el = document.querySelector("#app")
    this.$methods = options.methods
    this._bindings = {}
    // this._observe(this.$data)
    // this._compile(this.$el)
    console.log(this)

}
/* 给data添加绑定 */
myVue.prototype._observe = function(obj){
    const _this = this
    Object.keys(this.$data).forEach((key)=>{
        _this._bindings[key] = {
            _directives: []
        }
        let value = obj[key]
        if(typeof value === "object"){
            this._observe(value)
        }
        Object.defineProperty(obj, key, {
            enumerable: true,
            configurable: true,
            get: function(){
                return value
            },
            set: function(newVal){
                if(value !== newVal){
                    _this._bindings[key]._directives.forEach(item => item.update())
                }
            }
        })

    })
}
/* 解析模板上的指令 */
myVue.prototype._compile = function(root){
    console.log("root ", root)
    const nodes = root.children
    const _this = this
    for(const node of nodes){
        if(node.children.length !== 0){
            _this._compile(node)
        }
       
        if(node.hasAttribute("v-click")){
            const attrVal = node.getAttribute("v-click")
            node.onclick = _this.$methods[attrVal]
    
        }
        if(node.hasAttribute("v-model") && (node.tagName === "INPUT" || node.tagName === "TEXTAREA")){
            const attrVal = node.getAttribute("v-model")
            console.log("initINput")
            node.addEventListener = ("input", ()=>{
                _this._bindings[attrVal]._directives.push(new Watcher("input",node,_this,attrVal, "value"))
                return function(){
                    _this.$data[attrVal] = node.value
                }
            })()
        }
        if(el.hasAttribute("v-bind")){
            const attrVal = node.getAttribute("v-bind")
            _this._bindings[attrVal]._directives.push(new Watcher("text", el, _this, v, "innerHTML"))
        }
    }
    
}
function Wather(name, el, vm, exp, attr){
    this.name = name
    this.el = el
    this.vm = vm
    this.exp = exp
    this.attr = attr
    /* 初始化的时候，就进行更新一次 */
    this.update()
}
Wather.prototype.update = function(){
    const v = vm.$data[exp]
    this.el[this.attr] = this.vm.$data[this.exp]
    console.log("update "+this.attr)
}
console.log(document.querySelector("#app"))
console.log(document.querySelector(".box1"))
new myVue({
    el: "#app",
    data: {
        message: "hellow world"
    }
})

